from conf.operationConfig import OperationConfig
from common.recordlog import logs
import pymysql
from pymysql import cursors

class ConnectMysql:
    def __init__(self):
        mysql_conf = {"host":OperationConfig().get_section_mysql("host"),
                      "port":int(OperationConfig().get_section_mysql("port")),
                      "user":OperationConfig().get_section_mysql("username"),
                      "password":OperationConfig().get_section_mysql("password"),
                      "database":OperationConfig().get_section_mysql("database")
                      }

        try:
            self.conn = pymysql.connect(**mysql_conf,charset="utf8")
            # cursor=pymysql.cursors.DictCursor,将数据库表字段显示，以key-value形式展示
            self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            logs.info("""成功连接到mysql---
                        host：{host}
                        port：{port}
                        db：{database}
                        """.format(**mysql_conf))
        except Exception as e:
            logs.error(f"获取数据库连接对象失败 异常：{e}")

    def close(self):
        if self.conn or self.cursor:
            self.cursor.close()
            self.conn.close()
        return True

    def query_all(self,sql):
        try:
            self.cursor.execute(sql)
            res =self.cursor.fetchall()
            return res
        except Exception as e:
            logs.error(f"查询sql语句时发生错误 sql:{sql} 异常：{e}")


if __name__ == '__main__':
    conn = ConnectMysql().query_all("select * from student where name = 'zkkkkkk';")
    print(conn)
    print(type(conn))
